import logging

from agent.common.system import sysCommand
from agent.feature.base import Feature
from agent.common.tools import glob

logger = logging.getLogger('common')

class Readahead(Feature):
    __domain__ = "disk" 
    __feature__ = "readahead"
    
    def __init__(self):
        super().__init__(self.__domain__, self.__feature__)
        self.file_list = glob("/sys/block/*/queue/read_ahead_kb")
    
    def set_value(self, value):
        if type(value) is not list:
            if value.startswith(">"):
                value = value[1:]
            value = [value, ] * len(self.file_list)
        
        if len(value) != len(self.file_list):
            raise Exception("size unmatch: {} != {}".format(len(value), len(self.file_list)))
        
        for val, path in zip(value, self.file_list):
            sysCommand("echo {value} > {path}".format(
                value = val,
                path = path
            ),log=True)

    def get_value(self):
        values = []
        for path in self.file_list:
            values.append(int(
                sysCommand("cat {path}".format(path = path))))
        return values

if __name__ == "__main__":
    handler = Readahead()
    values = handler.get_value()
    handler.set_value(">4096")
    handler.set_value("128")
    handler.set_value(values)